import os
from pathlib import Path

from flask import flash
from werkzeug.utils import secure_filename

from common import utils


class ImageService:

    @staticmethod
    def get_image_dir():
        home_path = utils.get_home_path()
        image_path = home_path.joinpath('data/images')
        if not image_path.exists():
            Path.mkdir(image_path, parents=True)
        return image_path

    @staticmethod
    def get_image_file_fullname(image_file):
        image_path = ImageService.get_image_dir()
        image_file_fullname = image_path.joinpath(image_file)
        return image_file_fullname

    def upload_image(self, image_file):
        image_file_name = secure_filename(image_file.filename)
        image_file_fullname = ImageService.get_image_file_fullname(image_file_name)
        if not image_file_fullname.exists():
            pass
        else:
            index = image_file_name.rfind('.')
            prename = image_file_name[:index]
            postname = image_file_name[index+1:]
            for i in range(100):
                i +=1
                if not image_file_fullname.exists():
                    break
                image_file_name = f'{prename}_{i}.{postname}'
                image_file_fullname = ImageService.get_image_file_fullname(image_file_name)

        image_file.save(image_file_fullname)
        flash(f'图片上传成功,文件位置:{image_file_fullname}', category='success')

    def get_image_name_list(self):
        image_dir = self.get_image_dir()
        image_filenames = []
        for image_file in image_dir.iterdir():
            image_filenames.append(image_file.name)
        return image_filenames